home *** CD-ROM | disk | FTP | other *** search
- Path: anvil.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: Problem Negating an Unsigned Char
- Date: 4 Mar 1996 13:18:08 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4hfmmgINN4t8@anvil.ugrad.cs.ubc.ca>
- References: <Dnnros.Lq.0.-s@hkusuc.hku.hk> <4he27sINNdel@keats.ugrad.cs.ubc.ca> <DnqMyr.4pF@cwi.nl>
- NNTP-Posting-Host: anvil.ugrad.cs.ubc.ca
-
- In article <DnqMyr.4pF@cwi.nl>, Dik T. Winter <dik@cwi.nl> wrote:
- >In article <4he27sINNdel@keats.ugrad.cs.ubc.ca> c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku) writes:
- >...
- > > >unsigned char a=0x11;
- > > >unsigned char b=0xEE;
- >...
- > > > if( a == ~b ) {
- >...
- > > >The c remains unchange, while it changes to 1 if I cast the ~b to unsigned
- > > >char as if( a == (unsigned char) ~b )
- > >
- > > The cast forces the integer value of ~b into an unsigned char, stripping
- > > high-order bits. The above will work only on machines with eight bit chars.
- > >
- > > To make it portable, you must manually mask for the lower eight bits:
- > >
- > > if (a == (~b & 0xff))
- >
- >And how would this work on machines with other than eight bit chars?
-
- Just fine, thank you. The C standard guarantees char to be at least eight bits
- wide. The original poster wants eight bit arithmetic; i.e. that the complement
- of 0x11 be equal to 0xEE. This is what he is testing for, and the above is how
- you get it.
-
- >Casting to unsigned char will work regardless the number of bits in a char.
-
- Casting to an unsigned quantity is implementation defined. Are you suggesting
- that the invocation of implementation defined behavior is more portable than a
- well-defined bit masking operation? You haven't read your K&R2 appendices, have
- you? Section A6.1 states that an integral type (i.e. signed or unsigned char or
- bitfield) is promoted to an int, if it can be represented by an int, or to an
- unsigned int otherwise. If it gets promoted to int, and the machine you are on
- is not two's complement, then a cast back to an unsigned, narrower type may not
- produce the right quantity.
-
- Suppose that the machine is sign and magnitude, and ints are 16 bits, whereas
- unsigned chars are 8 bits. Your 0xEE value gets promoted to an int:
- 0000 0000 1110 1110. Now, you take the complement: 1111 1111 0001 0001.
- This is just the sign + magnitude representation of -0111 1111 0001 0001, in
- other words -32529.
-
- When you cast that to the narrower unsigned char type, the result is the least
- positive residue of that value modulo 2^8. (K&R 6.1A). This is just 239.
-
- 239 in hex is 0xEF
-
- it is not 0xEE.
-
- Do you still think that a cast will work regardless of the number of bits in a
- char?
- --
-
-